<template>
<div>
    <el-upload
        class="avatar-uploader"
        :action="'http://47.97.244.147:2333/api/user/userAvatarUpload/'+userId"
        :show-file-list="false"
        :on-success="handleAvatarSuccess"
        :on-error="handleAvatarError"
        :on-progress="handleAvatarProgress"
        :before-upload="beforeAvatarUpload">
        <el-avatar v-if="imageUrl" shape="circle" :size="130" fit="fill" :src="imageUrl"></el-avatar>
        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
    </el-upload>
</div>
</template>

<script>
export default {
    name:"userAvatarUpload",
    props:{
        userId:{
            required:true
        },
        imageUrl:{
            required:true
        }
    },
    data(){
        return {
            progressing:null //是否正在上传
        }
    },
    methods:{
        handleAvatarError(res,file){
            this.progressing.close();
            this.$message.error('图片上传失败!');
        },
        handleAvatarProgress(res,file){
            this.progressing = this.$loading({
                        lock: true,
                        text: '努力上传中',
                        spinner: 'el-icon-loading',
                        background: 'rgba(0, 0, 0, 0.7)'
                        });
        },
        handleAvatarSuccess(res, file) {
            console.log(res);
            console.log(file);
            this.progressing.close();
            if(res.status==="ok"){
                this.$emit("uploadSuccess",res.imageUrl);
            }else{
                this.$message.error('图片上传保存失败!');
            }
        },
        beforeAvatarUpload(file) {
            const isImage=file.type === 'image/jpeg'||file.type === 'image/png'||file.type === 'image/gif';
            const isLt10M = file.size / 1024 / 1024 < 10;
            if (!isImage) {
                this.$message.error('上传头像图片只能是 jpg或者png或者gif 格式!');
            }
            if (!isLt10M) {
                this.$message.error('上传头像图片大小不能超过 10MB!');
            }
            return isImage && isLt10M;
            }
    }
}
</script>

<style>
.avatar-uploader .el-upload {
border: 1px dashed #d9d9d9;
border-radius: 6px;
cursor: pointer;
position: relative;
overflow: hidden;
}
.avatar-uploader .el-upload:hover {
border-color: #409EFF;
}
.avatar-uploader-icon {
font-size: 28px;
color: #8c939d;
width: 178px;
height: 178px;
line-height: 178px;
text-align: center;
}
</style>